package com.changgou.controller;

import com.changgou.common.pojo.Page;
import com.changgou.search.feign.SkuFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private SkuFeign skuFeign;

    @GetMapping("/list")
    public String list(@RequestParam(required = false) Map<String,String> searchMap, Model model){
        Map resultMap = skuFeign.search(searchMap);
        model.addAttribute("result",resultMap);
        model.addAttribute("searchMap",searchMap);
        String url = url(searchMap);
        model.addAttribute("url",url);
        Page page = new Page(Long.valueOf(resultMap.get("total").toString()), Integer.valueOf(resultMap.get("pageNum").toString()), Integer.valueOf(resultMap.get("pageSize").toString()));
        model.addAttribute("page",page);
        return "search";
    }

    private String url(Map<String, String> searchMap) {
        String url = "/search/list";
        if(searchMap != null &&searchMap.size()>0){
            url+="?";
            for (Map.Entry<String, String> stringStringEntry : searchMap.entrySet()) {
                String value = stringStringEntry.getValue();
                String key = stringStringEntry.getKey();
                if(key.equalsIgnoreCase("pageNum")){
                    continue;
                }
                url= url +key+"="+value+"&";
            }
            url = url.substring(0,url.length()-1);
        }
        return url;
    }
}
